package com.sun.newapp;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.github.dfqin.grantor.PermissionListener;
import com.github.dfqin.grantor.PermissionsUtil;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.event.OnClick;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends Activity {
    private WebView webView;
    private ProgressBar progressBar;
    private Handler handler;
    private String imei;
    private String[] permissions = {
//            Manifest.permission.READ_PHONE_STATE,
//            ,Manifest.permission.READ_CONTACTS
//            ,Manifest.permission.CALL_PHONE
            Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.CAMERA
            ,Manifest.permission.VIBRATE,Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.ACCESS_FINE_LOCATION
            ,Manifest.permission.ACCESS_WIFI_STATE,Manifest.permission.ACCESS_NETWORK_STATE,Manifest.permission.CHANGE_WIFI_STATE
            };
    private String url;
    private Float scan;
    private int _time=3;

    @OnClick({R.id.ll_pc,R.id.ll_setting,R.id.ll_scan,R.id.ll_scanone})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.ll_pc:
                layDialog();
                break;
            case R.id.ll_setting:
                initwebview("/SET/");
                break;
            case R.id.ll_scanone:
                Intent intent=new Intent(MainActivity.this,ScanActivity.class);
                startActivityForResult(intent,1);
                break;
            case R.id.ll_scan:
                scanDialog();
//                singleDialog();
                break;
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ViewUtils.inject(this);
        imei = DeviceIdUtils.getLocalDeviceId(MainActivity.this);
        progressBar = (ProgressBar) findViewById(R.id.progressbar);//进度条
        webView = (WebView) findViewById(R.id.webview);
        url=SharedPreferencesUtils.getString(this,"url",null);
        if(url==null){
            url="scan.guito.cn";
            SharedPreferencesUtils.setString(this,"url",url);
        }
        PermissionsUtil.requestPermission(this, new PermissionListener() {
            @Override
            public void permissionGranted(String[] permission) {
//                MyUtils.showToast(MainActivity.this,"已同意");
                imei = DeviceIdUtils.getLocalDeviceId(MainActivity.this);
                Log.e("TAG",imei+"imei");
                initwebview("");
//                httpUtils.send(HttpRequest.HttpMethod.GET, "http://"+url+"?IMEI=" + imei, new RequestCallBack<String>() {
//                    @Override
//                    public void onSuccess(ResponseInfo<String> responseInfo) {
//                        Log.e("TAG", responseInfo.result+"????"+MobileInfoUtil.getValueByName(responseInfo.result,"TT"));
////                        String url=Environment.getExternalStorageDirectory() + "/Android/data/com.brower.sun/mainbg.jpg";
////                        File file=new File(url);
////                        if(file.exists()){
////                            file.delete();
////                        }
//                        httpUtils.download(responseInfo.result, Environment.getExternalStorageDirectory() + "/Android/data/com.brower.sun/"+System.currentTimeMillis()+".jpg", new RequestCallBack<File>() {
//                            @Override
//                            public void onSuccess(ResponseInfo<File> responseInfo) {
//                                Log.e("TAG",responseInfo.result.getAbsolutePath());
//                                SharedPreferencesUtils.setString(MainActivity.this,"image",responseInfo.result.getAbsolutePath());
//                            }
//
//                            @Override
//                            public void onFailure(HttpException error, String msg) {
//                                Log.e("TAG",msg);
//                            }
//                        });
//                        initwebview("");
//                    }
//
//                    @Override
//                    public void onFailure(HttpException e, String s) {
//                        Log.e("TAG", s);
//                    }
//                });
            }

            @Override
            public void permissionDenied( String[] permission) {
//                .showToast(MainActivity.this, "已拒绝，程序可能无法使用");
                Toast.makeText(MainActivity.this,"已拒绝，程序可能无法使用",Toast.LENGTH_SHORT);
            }
        }, permissions, true, new PermissionsUtil.TipInfo("授权", "为了保证程序的正常运行，请授予我权限！", "不同意", "同意"));
    }
    private void initwebview(String path) {
        if(TextUtils.isEmpty(imei)){
            imei=getUniqueId(this);
        }
        if(path.startsWith("http")){
            webView.loadUrl(path);//加载url
        }else {
            webView.loadUrl("http://"+url+path+"?IMEI=" + imei+"&VER=2.0");//加载url
        }
        //使用webview显示html代码
//        webView.loadDataWithBaseURL(null,"<html><head><title> 欢迎您 </title></head>" +
//                "<body><h2>使用webview显示 html代码</h2></body></html>", "text/html" , "utf-8", null);
        webView.addJavascriptInterface(this, "android");//添加js监听 这样html就能调用客户端
        webView.setWebChromeClient(webChromeClient);
        webView.setWebViewClient(webViewClient);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);//允许使用js
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
//        handler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
////                        webView.setVisibility(View.VISIBLE);
//                    }
//                });
//            }
//        }, 3000);
        /**
         * LOAD_CACHE_ONLY: 不使用网络，只读取本地缓存数据
         * LOAD_DEFAULT: （默认）根据cache-control决定是否从网络上取数据。
         * LOAD_NO_CACHE: 不使用缓存，只从网络获取数据.
         * LOAD_CACHE_ELSE_NETWORK，只要本地有，无论是否过期，或者no-cache，都使用缓存中的数据。
         */
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);//不使用缓存，只从网络获取数据.
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        //支持屏幕缩放
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);
        webSettings.setDefaultTextEncodingName("GBK");

        //不显示webview缩放按钮
        webSettings.setDisplayZoomControls(false);
    }

    //WebViewClient主要帮助WebView处理各种通知、请求事件
    private WebViewClient webViewClient = new WebViewClient() {
        @Override
        public void onPageFinished(WebView view, String url) {//页面加载完成
            progressBar.setVisibility(View.GONE);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {//页面开始加载
            progressBar.setVisibility(View.VISIBLE);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.i("ansen", "拦截url:" + url.toLowerCase());
            if (url.equals("http://www.google.com/")) {
                Toast.makeText(MainActivity.this, "国内不能访问google,拦截该url", Toast.LENGTH_LONG).show();
                return true;//表示我已经处理过了
            }
//            if(url.toLowerCase().contains("RENEWIMEI=1")){
////                Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
////                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
////                startActivity(i);
//                imei = DeviceIdUtils.getLocalDeviceId(MainActivity.this);
//                Log.e("TAG",imei+"imei");
//                initwebview("");
//            }
            if (url.startsWith("tel:")) {
                Intent intent = new Intent(Intent.ACTION_VIEW,
                        Uri.parse(url));
                startActivity(intent);
                return true;
            }

            return super.shouldOverrideUrlLoading(view, url);
        }

    };

    private AlertDialog.Builder builder;
    private AlertDialog alertDialog;
    //WebChromeClient主要辅助WebView处理Javascript的对话框、网站图标、网站title、加载进度等
    private WebChromeClient webChromeClient = new WebChromeClient() {
        //不支持js的alert弹窗，需要自己监听然后通过dialog弹窗
        @Override
        public boolean onJsAlert(WebView webView, String url, String message, final JsResult result) {

            //注意:
            //必须要这一句代码:result.confirm()表示:
            //处理结果为确定状态同时唤醒WebCore线程
            //否则不能继续点击按钮
            Log.e("TAG",url+message);
            builder = new AlertDialog.Builder(MainActivity.this);
            alertDialog = builder.setTitle("提示信息:")
                    .setMessage(message)
                    .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            result.confirm();
                        }
                    }).create();
            alertDialog.show();
            return true;
        }

        //获取网页标题
        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            Log.i("ansen", "网页标题:" + title);
        }

        //加载进度回调
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            progressBar.setProgress(newProgress);
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.i("ansen", "是否有上一个页面:" + webView.canGoBack());
        if (webView.canGoBack() && keyCode == KeyEvent.KEYCODE_BACK) {//点击返回按钮的时候判断有没有上一页
            webView.goBack(); // goBack()表示返回webView的上一页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==1){
            if(requestCode==1&&data!=null){
                String result=data.getStringExtra("data");
                final float scan=data.getFloatExtra("scan",1);
                Log.e("TAG返回数据",result+"scan"+scan);
                initwebview(result);
                if(scan>0){
                    TimerTask task = new TimerTask() {
                        @Override
                        public void run() {
                            //要执行的操作
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Intent intent=new Intent(MainActivity.this,ScanActivity.class);
                                    intent.putExtra("scan",scan);
                                    startActivityForResult(intent,1);
                                }
                            });
                        }
                    };
                    Timer timer = new Timer();
                    timer.schedule(task, (long) (scan*1000));//2秒后执行TimeTask的run方法
                }
            }
//            initwebview("");
        }
    }

    /**
     * JS调用android的方法
     *
     * @param str
     * @return
     */
    @JavascriptInterface //仍然必不可少
    public void getClient(String str) {
        Log.i("ansen", "html调用客户端:" + str);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        //释放资源
        webView.destroy();
        webView = null;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    /**
     * 字符串转换为Ascii
     *
     * @param value
     * @return
     */
    public int stringToAscii(String value) {
        int number = 0;
        StringBuffer sbu = new StringBuffer();
        char[] chars = value.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (i != chars.length - 1) {
                sbu.append((int) chars[i]).append(",");
            } else {
                sbu.append((int) chars[i]);
            }
            number += (int) chars[i];
        }
        Log.e("TAG", sbu.toString());
        return number;

    }


    public int getUserDate() {
        int number = 0;
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        String dateString = formatter.format(currentTime);
        Log.e("TAG", dateString);
        String[] datas = dateString.split("-");
        for (String data : datas) {
            number += Integer.valueOf(data);
        }
        return number;
    }
    public  String getUniqueId(Context context){
        String androidID = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
        String id = androidID + Build.SERIAL;
        return id;
//        try {
//            return toMD5(id);
//        } catch (NoSuchAlgorithmException e) {
//            e.printStackTrace();
//            return id;
//        }
    }
    /**
     * 自定义布局的对话框
     */
    private void layDialog() {
        _time=3;
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

        // 创建一个view，并且将布局加入view中
        View view = LayoutInflater.from(MainActivity.this).inflate(
                R.layout.dialog_edt, null, false);
        // 将view添加到builder中
        builder.setView(view);
        // 创建dialog
        final Dialog dialog = builder.create();
        // 初始化控件，注意这里是通过view.findViewById
        final EditText edt = (EditText) view.findViewById(R.id.et_url);
        final TextView tv_url = (TextView) view.findViewById(R.id.tv_url);
        edt.setText(url);
        tv_url.setText(url);
        final Button confirm = (Button) view.findViewById(R.id.btn_edit);
        final Button cancel = (Button) view.findViewById(R.id.btn_cacle);
        // 设置button的点击事件及获取editview中的文本内容
        confirm.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                if(confirm.getText().toString().equals("保存")){
                    String str = edt.getText() == null ? "" : edt.getText()
                            .toString();
                    url=str;
                    //判断域名是否可用
                    Process p1 = null;
                    try {
                        p1 = Runtime.getRuntime().exec("ping -c 1 -w 100 " + url);
                        int status1 = p1.waitFor();
                        if (status1 == 0) {

                            //域名能ping通，有效
                            SharedPreferencesUtils.setString(MainActivity.this,"url",str);
                            dialog.dismiss();
                            initwebview("");
                        } else {
                            //域名ping不通
                            MyUtils.showToast(MainActivity.this,"无效的服务器");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }else {
                    confirm.setText("保存");
                    cancel.setText("恢复");
                    handler.removeCallbacksAndMessages(null);
                    tv_url.setVisibility(View.GONE);
                    edt.setVisibility(View.VISIBLE);
                    edt.requestFocus();
                }
            }
        });
        // 取消按钮
        cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
//                dialog.dismiss();
                handler.removeCallbacksAndMessages(null);
                dialog.dismiss();
                initwebview("");
                if(cancel.getText().toString().equals("连接")){
                    cancel.setText("恢复");
                }else {
                    url=SharedPreferencesUtils.getString(MainActivity.this,"url",null);
                    initwebview("");
                }
            }
        });
        dialog.show();
        handler = new Handler();
        handler.post(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                if(_time<=0){
                    if(dialog.isShowing()){
                        dialog.dismiss();
                        handler.removeCallbacksAndMessages(null);
                        initwebview("");
                    }
                }else{
                    confirm.setText("设置（"+(_time)+"）");
                    _time--;
                    handler.postDelayed(this, 1000);
                }
            }
        });
//        TimerTask task = new TimerTask() {
//            @Override
//            public void run() {
//
//                //要执行的操作
//                runOnUiThread(new Runnable() {
//                    @Override
//                    public void run() {
//                        if(dialog.isShowing()){
//                            dialog.dismiss();
//                            initwebview("");
//                        }
//                    }
//                });
//            }
//        };
//        Timer timer = new Timer();
//        timer.schedule(task, (long) (3*1000));//2秒后执行TimeTask的run方法
    }

    private String str;
    /**
     * 自定义布局的对话框
     */
    private void scanDialog() {

        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

        // 创建一个view，并且将布局加入view中
        View view = LayoutInflater.from(MainActivity.this).inflate(
                R.layout.dialog_scan, null, false);
        // 将view添加到builder中
        builder.setView(view);
        // 创建dialog
        final Dialog dialog = builder.create();
        // 初始化控件，注意这里是通过view.findViewById
        final Spinner spinner = (Spinner) view.findViewById(R.id.spinner);
//        edt.setText("1");
        scan=SharedPreferencesUtils.getFloat(MainActivity.this,"scan",1);
        int position=1;
        if (scan==0.5){
            position=0;
        }
        else if(scan==1){
            position=1;
        }
        else if(scan==1.5){
            position=2;
        }
        else if(scan==2){
            position=3;
        }
        else if(scan==2.5){
            position=4;
        }
        else if(scan==3){
            position=5;
        }
        else if(scan==3.5){
            position=6;
        }
        else if(scan==4){
            position=7;
        }
        else if(scan==4.5){
            position=8;
        }
        else if(scan==5){
            position=9;
        }
        spinner.setSelection(position);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                //拿到被选择项的值
                str = (String) spinner.getSelectedItem();
                Log.e("TAG",str);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        Button confirm = (Button) view.findViewById(R.id.btn_edit);
        Button cancel = (Button) view.findViewById(R.id.btn_cacle);
        // 设置button的点击事件及获取editview中的文本内容
        confirm.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
//                String str = edt.getText() == null ? "" : edt.getText()
//                        .toString();
                scan=Float.valueOf(str);
                if(scan<0.5||scan>5){
                    MyUtils.showToast(MainActivity.this,"扫码时间间隔必须是是0.5-5秒之间");
                }else {
                    SharedPreferencesUtils.setFloat(MainActivity.this,"scan",scan);
                    Intent intent=new Intent(MainActivity.this,ScanActivity.class);
                    intent.putExtra("scan",scan);
                    startActivityForResult(intent,1);
                }
                dialog.dismiss();
            }
        });
        // 取消按钮
        cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                dialog.dismiss();
            }
        });
        dialog.show();
    }
}
